package com.lydms.service.impl;


import com.lydms.pojo.Email;
import com.lydms.pojo.English;
import com.lydms.service.WordEmailService;
import com.lydms.service.WordSelectService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.internet.MimeMessage;
import java.io.File;
import java.util.List;

@Service
public class WordEmailServiceImpl implements WordEmailService {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private JavaMailSender sender;

    @Autowired
    private WordSelectService wordSelectService;

    @Value("${spring.mail.username}")
    private String formMail;

    /**
     * 发送普通邮件
     *
     * @param toMail
     * @param subject
     * @param content
     */
    public void sendSimpleMail(String toMail, String subject, String content) {
        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
        simpleMailMessage.setFrom(formMail);
        simpleMailMessage.setTo(toMail);
        simpleMailMessage.setSubject(subject);
        simpleMailMessage.setText(content);
        try {
            sender.send(simpleMailMessage);
            logger.info("发送给" + toMail + "简单邮件已经发送。 subject：" + subject);
        } catch (Exception e) {
            logger.info("发送给" + toMail + "send mail error subject：" + subject);
            e.printStackTrace();
        }
    }

    /**
     * 发送带Html格式邮件
     *
     * @param toMail
     * @param subject
     * @param content
     */
    public void sendHtmlMail(String toMail, String subject, String content) {
        MimeMessage mimeMessage = sender.createMimeMessage();
        try {
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
            mimeMessageHelper.setTo(toMail);
            mimeMessageHelper.setFrom(formMail);
            mimeMessageHelper.setText(content, true);
            mimeMessageHelper.setSubject(subject);
            sender.send(mimeMessage);
            logger.info("发送给" + toMail + "html邮件已经发送。 简介：" + subject);
        } catch (Exception e) {
            logger.info("发送给" + toMail + "html send mail error subject：" + subject);
            e.printStackTrace();
        }
    }


    /**
     * 发送静态资源（一般是图片）的邮件
     *
     * @param
     * @param subject
     * @param content 邮件内容，需要包括一个静态资源的id，比如：<img src=\"cid:image\" >
     * @param
     */
    public void sendHtmlPhotoMail(String to, String subject, String content, List<Email> resourceist) {


        MimeMessage message = sender.createMimeMessage();

        try {
            //true表示需要创建一个multipart message
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(formMail);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);
            for (Email email : resourceist) {
                FileSystemResource res = new FileSystemResource(new File(email.getPath()));
                helper.addInline(email.getCid(), res);
            }
            sender.send(message);
            logger.info("嵌入静态资源的邮件已经发送。");
        } catch (Exception e) {
            logger.error("发送嵌入静态资源的邮件时发生异常！", e);
        }
    }


    /**
     * 发送普通邮件
     *
     * @param toMail
     * @param subject
     * @param content
     */
    public void sendFileMail(String toMail, String subject, String content, String filePath) {
        MimeMessage message = sender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(formMail);
            helper.setTo(toMail);
            helper.setSubject(subject);
            helper.setText(content, true);
            FileSystemResource file = new FileSystemResource(new File(filePath));
            String fileName = filePath.substring(filePath.lastIndexOf("/"));
            helper.addAttachment(fileName, file);
            sender.send(message);
            logger.info("发送给" + toMail + "带附件的邮件已经发送。");
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("发送给" + toMail + "带附件的邮件时发生异常！", e);
        }
    }


    /**
     * 查询指定分类2天数的数据（不传返回当天数据）
     *
     * @param day
     * @return Html类型的当天数据
     */
    @Override
    public String getHtmlEmailByDay(String day) {

//        查询出指定天数的数据
        List<English> en = wordSelectService.selectToday(day);
//        将查询出来的结果拼接为HTML格式
        String start = "<!DOCTYPE html><html><head><meta charset=\"utf-8\"><title></title></head><body><font color=\"red\">少一些功利主义的追求！多一些不问为什么的坚持！</font><table border=\"1\"><tr><th>英文</th><th>标准注解</th><th>代码中注解</th></tr>";
        String prime = "";
        for (int i = 0; i < en.size(); i++) {
            English selectRsult = en.get(i);
            String center = "<tr><td>Id</td><td>English</td><td>Chinese</td><td>CodeChinese</td></tr>";
            String english = selectRsult.getEnglish();
            String chinese = selectRsult.getChinese();
            if (chinese == null) {
                chinese = "";
            }
            String codeChinese = selectRsult.getCodechinese();
            if (codeChinese == null) {
                codeChinese = "";
            }
            String one = center.replaceFirst("Id", String.valueOf(i+1));
            String two = one.replaceFirst("English", english);
            String three = two.replaceFirst("Chinese", chinese);
            String result = three.replaceFirst("CodeChinese", codeChinese);
            prime = prime + result;
        }
        String end = "</table></body></html>";
//        最后拼接结果
        String html = start + prime + end;

        logger.info("拼接后的Html格式文件内容为:{}", html);
        return html;
    }

}
